<template>
	<view class="search-page">
		<view class="search">
			<uv-search :placeholder="tips" v-model="keyword" @search="handSearch" @custom="handSearch"></uv-search>
		</view>
		<view class="history" v-if="historyList.length > 0">
			<view class="nav">
				<text class="title">搜索历史</text>
				<view @click="handDel">
					<uv-icon name="trash" color="#666666" size="26"></uv-icon>
				</view>
			</view>
			<view class="tags">
				<button class="cu-btn" v-for="(item, index) in historyList" :key="index"
					@click="handSearchText(item.searchContent)">
					{{ item.searchContent }}
				</button>
			</view>
		</view>
		<view class="history" style="margin-top: 48rpx;" v-if="horList.length > 0">
			<view class="nav">
				<text class="title">热门搜索</text>
			</view>
			<view class="tags">
				<button class="cu-btn" v-for="(item, index) in horList" :key="index"
					@click="handSearchText(item.searchContent)">
					{{ item.searchContent }}
				</button>
			</view>
		</view>
		<uv-modal ref="modal" show-cancel-button confirm-color="#FF9113" @confirm="handConfirm" width="550rpx">
			<view style="line-height: 100rpx;">确认要删除吗?</view>
		</uv-modal>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		inject
	} from 'vue'
	import {
		doHor,
		doLogList,
		doDelLog
	} from '@/apis/search.js'
	import {
		onLoad
	} from "@dcloudio/uni-app";

	const $back = inject('$back')

	const keyword = ref('')
	const historyList = ref([])
	const horList = ref([])

	const modal = ref()
	const handConfirm = async () => {
		historyList.value = []
		await doDelLog()
	}

	const handDel = () => {
		modal.value.open()
	}

	const handBack = () => {
		$back()
	}

	const handSearch = () => {
		if (!keyword.value) {
			uni.$uv.toast('请输入搜索关键字')
			return
		}
		handSearchText(keyword.value)
	}

	const handSearchText = (e) => {
		uni.navigateTo({
			url: `/pages/search/list?name=${e}`
		})
	}

	let tips = ref("")
	onLoad(() => {
		Promise.all([doHor(), doLogList()]).then(res => {
			horList.value = res[0].records
			if (res[0].records.length > 0) {
				tips.value = `大家都在搜“${res[0].records[0].searchContent}”`
			} else {
				tips.value = '请输入搜索关键字'
			}
			historyList.value = res[1].records
		})
	})
</script>

<style lang="scss" scoped>
	.search-page {
		padding: 24rpx;

		.history {
			margin-top: 40rpx;

			.nav {
				display: flex;
				align-items: center;
				justify-content: space-between;

				.title {
					font-size: 30rpx;
					font-family: PingFang SC-Bold, PingFang SC;
					font-weight: bold;
					color: #333333;
				}
			}

			.tags {
				margin-top: 32rpx;
				display: flex;
				flex-wrap: wrap;
				gap: 16rpx;

				.cu-btn {
					font-size: 26rpx;
					height: 56rpx;
					line-height: 56rpx;
					font-family: PingFang SC-Regular, PingFang SC;
					font-weight: 400;
					color: #666666;
					padding: 0 32rpx;
					background: #F5F5F5;
					border-radius: 30rpx;
					margin: 0;

					&::after {
						border: none;
					}
				}
			}
		}
	}
</style>